//
//  NetWork.m
//  BBT
//
//  Created by Monkxp on 15/9/6.
//  Copyright (c) 2015年 QCKJ. All rights reserved.
//

#import "NetWork.h"
#import "LoginModel.h"

@implementation NetWork{
    
}

+(BOOL)netWorkStatus{
    
    /**
     *  AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     *  AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     *  AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G/4G
     *  AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络Wifi
     */
    // 如果要检测网络状态的变化, 必须要用检测管理器的单例startMoitoring
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status == AFNetworkReachabilityStatusNotReachable){
            NSLog(@"网络连接已断开，请检查您的网络！");
            [Utils showHudWithTitle:@"网络似乎跑丢了，请检查您的网络！" delay:1.0f target:nil];
            return ;
        }
    }];
    return YES;
    
}



#pragma mark - post -
+ (void)post:(NSString *)url params:(NSDictionary *)params success:(responseBlock)successHandler failure:(requestFailure)failureHandler{
    if (![NetWork netWorkStatus]) {
        [Utils showHudWithTitle:@"当前无可用网络" delay:2 target:nil];
        return;
    }
    AFHTTPRequestOperationManager *mgr = [self getRequstManager];
    [mgr POST:[self compeletHttpUrlWithSubUrl:url] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObj) {
        [self printHttpWithOperation:operation withResponseObj:responseObj withManager: mgr];
        !successHandler?:successHandler(responseObj);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { !failureHandler?:failureHandler(error);}];
}

#pragma mark - put -
+ (void)put:(NSString *)url params:(NSDictionary *)params success:(responseBlock)successHandler failure:(requestFailure)failureHandler{
    if (![NetWork netWorkStatus]) {
        [Utils showHudWithTitle:@"当前无可用网络" delay:2 target:nil];
        return;
    }
    AFHTTPRequestOperationManager *mgr = [self getRequstManager];
    [mgr PUT:[self compeletHttpUrlWithSubUrl:url] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObj) {
        [self printHttpWithOperation:operation withResponseObj:responseObj withManager: mgr];
        !successHandler?:successHandler(responseObj);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {!failureHandler?:failureHandler(error);}];
}

#pragma mark - delete-
+ (void)deleteRequest:(NSString *)url params:(NSDictionary *)params success:(responseBlock)successHandler failure:(requestFailure)failureHandler;{
    if (![NetWork netWorkStatus]) {
        [Utils showHudWithTitle:@"当前无可用网络" delay:2 target:nil];
        return;
    }
    AFHTTPRequestOperationManager *mgr = [self getRequstManager];
    [mgr DELETE:[self compeletHttpUrlWithSubUrl:url] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObj) {
        [self printHttpWithOperation:operation withResponseObj:responseObj withManager:mgr];
        !successHandler?:successHandler(responseObj);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {!failureHandler?:failureHandler(error);}];
}

#pragma mark- 处理url 拼接host
+(NSString *)compeletHttpUrlWithSubUrl:(NSString *)subUrl
{
    if ([subUrl hasPrefix:@"http://"]) {
        return subUrl;
    }
    return [NSString stringWithFormat:@"http://%@/%@",MAIN_URL, subUrl];
}

+(NSString *)compeletHttpUrlWithSubUrl1:(NSString *)subUrl
{
    if ([subUrl hasPrefix:@"http://"]) {
        return subUrl;
    }
    return [NSString stringWithFormat:@"http://%@/%@",MAIN_URL, subUrl];
}


#pragma mark- AFHTTPRequestOperationManager初始化 网络超时设置 请求头
+(AFHTTPRequestOperationManager *)getRequstManager{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 设置token
    NSString *Authorization = [[NSUserDefaults standardUserDefaults] objectForKey:@"access_token"];
    if (Authorization) {
        [mgr.requestSerializer setValue:Authorization forHTTPHeaderField:@"Bearer Token"];
    }
    // [mgr.requestSerializer setValue:@"" forHTTPHeaderField:@"access_token"];
    
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    
     mgr.requestSerializer.timeoutInterval = 20;
    return mgr;
}

#pragma mark- 打印url 和 json数据 httpHeader用于调试
+(void)printHttpWithOperation:(AFHTTPRequestOperation *)operation withResponseObj:(id)responseObj withManager:(AFHTTPRequestOperationManager *)mgr{
#if DEBUG
    // 请求的url
    // NSLog(@"fianlUrl: %@", operation.request.URL.absoluteString);
    
    // 请求的json数据打印
    // NSData *dataJson = [NSJSONSerialization dataWithJSONObject:responseObj options:NSJSONWritingPrettyPrinted error:nil];
    // NSString *jsonStr = [[NSString alloc] initWithData:dataJson encoding:NSUTF8StringEncoding];
    // NSLog(@"dataJson: %@", jsonStr);
    
    // 请求的header信息
    // NSDictionary *dict = mgr.requestSerializer.HTTPRequestHeaders;
    // NSLog(@"请求头httpHeader: %@", dict);
#endif
}



+(NSDictionary *)imagesUUID:(NSArray *)images{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    for (int i = 0 ; i<images.count; i++) {
        NSString *uuid = [[NSUUID UUID] UUIDString];
        [dic setObject:images[i] forKey:uuid];
    }
    return [dic copy];
}


#pragma mark - get -
+ (void)get:(NSString *)url params:(NSDictionary *)params success:(responseBlock)successHandler failure:(requestFailure)failureHandler{
    if (![NetWork netWorkStatus]) {
        [Utils showHudWithTitle:@"当前无可用网络" delay:2 target:nil];
        return;
    }
    AFHTTPRequestOperationManager *mgr = [self getRequstManager];
    [mgr GET:[self compeletHttpUrlWithSubUrl:url] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObj) {
        [self printHttpWithOperation:operation withResponseObj:responseObj withManager:mgr];
        !successHandler?:successHandler(responseObj);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        !failureHandler?:failureHandler(error);
    }];
}





+(NSString*)forDic:(NSDictionary*)dic{
    
    NSString *strAll = @"";
    NSString *str = @"";
    
    if (dic!=nil) {
        NSArray *arrayAllKey = [dic allKeys];
        for (NSInteger i = 0; i<arrayAllKey.count; i++) {
            str = @"";
            if ([dic objectForKey:[arrayAllKey objectAtIndex:i]]!=nil) {
                str = [NSString stringWithFormat:@"%@=%@",[arrayAllKey objectAtIndex:i],[dic objectForKey:[arrayAllKey objectAtIndex:i]]];
            }else{
                str = [NSString stringWithFormat:@"%@=",[arrayAllKey objectAtIndex:i]];
            }
            
            strAll = [NSString stringWithFormat:@"%@%@&",strAll,str];
        }
        if (str.length > 0) {
            strAll = [strAll substringToIndex:strAll.length - 1];
        }
    }
    return strAll;
}









#pragma mark - get request
+ (void)getDataWithString:(NSString *)string parma:(NSDictionary *)parma SuccessBlock:(AFNSuccessDataBlock)succsessBlock FailBlock:(AFNFailDataBlock)failBlock{

    AFNetworkReachabilityManager *netWorkingManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = [NSString stringWithFormat:@"%@%@?%@",MAIN_URL, string, [self forDic:parma]];
    NSLog(@"requestURL:%@",url_string);
    NSURL *URL = [NSURL URLWithString:url_string];
    url_string = [url_string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    if (kAccess_token) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", kAccess_token] forHTTPHeaderField:@"Authorization"];
        
    }
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/json", @"application/json", @"text/javascript", @"text/html",  nil];
    [manager GET:URL.absoluteString parameters:parma success:^(NSURLSessionTask *task, id responseObject) {
        [netWorkingManager stopMonitoring];
        if (succsessBlock) {
            !succsessBlock?:succsessBlock(responseObject);
        }
        
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        if (failBlock) {
            
            failBlock (error);
        }
    }];
    
}


#pragma mark - post request
+(void)postDataWithString:(NSString *)string body:(NSDictionary *)parameters successBlock:(PostSuccessBlock)successBlock failBlock:(PostFailBlock)failBlock{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [Utils closeHud];
    });
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//
//    // 因为传递过去和接收回来的数据都不是json类型的，所以在这里要设置为AFHTTPRequestSerializer和AFHTTPResponseSerializer
//    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
//    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
    
    
    NSString *url_string = [NSString stringWithFormat:@"%@%@",MAIN_URL,string];
    if ([string containsString:@"http"]) {
        url_string = string;
    }
    NSLog(@"urlString:%@",[NSString stringWithFormat:@"%@?%@",url_string, [self forDic:parameters]]);
    
    url_string = [url_string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer.timeoutInterval = 5;
    
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    if (kAccess_token) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", kAccess_token] forHTTPHeaderField:@"Authorization"];
        
    }
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    

//    [mgr POST:url_string parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        if (successBlock) {
////            id string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//            id ss = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//            successBlock(ss);
//        }
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
//        if (failBlock) {
//            failBlock(error);
//        }
//    }];
    [manager POST:url_string parameters:parameters success:^(NSURLSessionTask *task, id responseObject)  {
        
        [netWorkManager stopMonitoring];
        if (successBlock) {
            successBlock(responseObject);
        }
        
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
        if (failBlock) {
            failBlock(error);
        }
        //        NSLog(@"失败 === %@",error);
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //
        //            NSLog(@"Error: %@", error);
        //        });
    }];
    
}

+ (BOOL)isContainsChinese:(NSString *)str{
    
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}


- (void)refreshLoadToken{
    RefreshVM *vm;
    vm = [RefreshVM new];
    vm.urlStr = @"/api/authorizations";
    vm.params = [self configParam];
    vm.dataClass = [LoginModel class];
    [vm requestDataNormal];
    [vm setRequestResultBlock:^(id obj) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        LoginModel *model = obj;
        [user setObject:model.access_token forKey:@"access_token"];
//        NSLog(@"%ld", (long)model.expires_in);
        
    }];
}

-(NSDictionary *)configParam{
    
    NSString *password  =  [[NSUserDefaults standardUserDefaults]objectForKey:@"password"];
    NSString * account= [[NSUserDefaults standardUserDefaults]objectForKey:@"account"];
    
    return @{@"account": account, @"password": password};
}

#pragma mark - 上传图片
+(void)uploadWithUrl:(NSString*)url Image:(UIImage *)image successBlock:(PostSuccessBlock)successBlock{
    
    NSData *data = UIImagePNGRepresentation(image);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [dic setObject:@"idcard_front" forKey:@"type"];
    [Utils showHudWithTitle:@"上传中" target:nil];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    if (kAccess_token) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", kAccess_token] forHTTPHeaderField:@"Authorization"];
    }
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        /**
         * 文件流方式上传
         */
        [formData appendPartWithFileData:data name:@"image" fileName:@"image.jpg" mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation,id responseObject) {
        [Utils closeHud];
        NSLog(@"Success: %@", responseObject);
        [Utils closeHud];
        successBlock(responseObject);
//        if ([responseObject[@"count"] boolValue]) {
//        }else{
//            [Utils showHudWithTitle:responseObject[@"error"] delay:1.0f target:nil];
//        }
        
    } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
        NSLog(@"Error: %@", error);
        [Utils closeHud];
    }];
    
    
}
+(NSString *)imageBase64WithDataURL:(UIImage *)image{
    NSData *imageData =nil;
    NSString *mimeType =nil;
    
    //图片要压缩的比例，此处100根据需求，自行设置
    CGFloat x =100 / image.size.height;
    if (x >1)
    {
        x = 1.0;
    }
    imageData = UIImageJPEGRepresentation(image, x);
    mimeType = @"image/jpeg";
    return [NSString stringWithFormat:@"%@",
            [imageData base64EncodedStringWithOptions:0]];
}
//MD5
//+(NSString *)md5HexDigest:(NSString*)str{
//    const char *original_str = [str UTF8String];
//    unsigned char result[16];
//    NSNumber *num = [NSNumber numberWithUnsignedLong:strlen(original_str)];
//    CC_MD5( original_str,[num intValue], result );
//    return [[NSString stringWithFormat:
//             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
//             result[0], result[1], result[2], result[3],
//             result[4], result[5], result[6], result[7],
//             result[8], result[9], result[10], result[11],
//             result[12], result[13], result[14], result[15]
//             ] uppercaseString];
//
//}

@end
